package ch.ti.bfh.app.loodel.domain.timeslotvote;

import ch.ti.bfh.app.loodel.domain.member.Member;
import ch.ti.bfh.app.loodel.domain.timeslot.TimeSlot;
import com.mysema.query.annotations.QueryInit;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"timeSlot_id", "voter_id"}))
public class TimeSlotVote {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @NotNull
    // Used for Location Search of existing TimeSlotsVotes for current Member
    @QueryInit({"location", "learningEvent"})
    @JoinColumn(name = "timeSlot_id")
    private TimeSlot timeSlot;

    @ManyToOne
    @NotNull
    @JoinColumn(name = "voter_id")
    private Member voter;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime creationTime;

    @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime lastUpdatedTime;

    public TimeSlotVote(TimeSlot timeSlot, Member voter) {
        this.timeSlot = timeSlot;
        this.voter = voter;
    }

    @PreUpdate
    @PrePersist
    public void updateTimeStamps() {
        lastUpdatedTime = new DateTime();
        if (creationTime == null) {
            creationTime = new DateTime();
        }
    }

    public boolean conflictsWithOtherTimeSlot(TimeSlot timeslot) {
        return timeSlot.getInterval().abuts(timeslot.getInterval());
    }

    protected TimeSlotVote() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public TimeSlot getTimeSlot() {
        return timeSlot;
    }

    public void setTimeSlot(TimeSlot timeSlot) {
        this.timeSlot = timeSlot;
    }

    public Member getVoter() {
        return voter;
    }

    public void setVoter(Member voter) {
        this.voter = voter;
    }

    public DateTime getCreationTime() {
        return creationTime;
    }

    public DateTime getLastUpdatedTime() {
        return lastUpdatedTime;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof TimeSlotVote)) return false;

        TimeSlotVote that = (TimeSlotVote) o;

        if (id != null ? !id.equals(that.id) : that.id != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }
}
